<template>
  <el-drawer
    :append-to-body="true"
    :size="size"
    title="我是标题"
    :visible="show"
    @close="handleClose"
    :with-header="false"
  >
    <div class="fileContian">
      <div class="flexBet fileline">
        <div class="flex">
          <el-link
            style="margin-left: -20px; margin-right: 8px"
            @click="switchFullShow"
            :underline="false"
            type="primary"
          >
            <i :class="fullShow ? 'el-icon-right' : 'el-icon-back'"></i>
            {{ fullShow ? "关闭" : "全屏" }}
          </el-link>
          <img :src="returnIcon(showUrl.url, type)" alt="加载失败" />
          <tooltip
            :text="showName"
            class="shou filename"
            :width="'450'"
          ></tooltip>
        </div>
        <el-button
          v-preventReClick
          type="primary"
          v-if="downloadAbled"
          @click="download()"
          >下载
        </el-button>
      </div>
      <div class="label flexBet" v-if="isUrls">
        <div>
          <div class="flex">
            <div class="i1" v-if="showUrl.className" style="margin-right: 20px">
              行政班:{{ showUrl.className }}
            </div>
            <div class="i1" v-if="showUrl.studentName">
              {{ showUrl ? showUrl.studentName : showUrl.studentName }}({{
                showUrl.studentNum
              }})
            </div>
            <div class="i1" style="margin-left: 20px">
              {{ showUrl.createTime }}
            </div>
          </div>

          <tooltip :text="showUrl.ancestorsName" width="610" class="i2">
            {{ showUrl.ancestorsName }}
          </tooltip>
        </div>
        <div>{{ index + 1 }}/{{ url.length }}</div>
      </div>
      <div
        class="show"
        :style="{
          height: isUrls ? 'calc(100vh - 199px)' : 'calc(100vh - 70px)',
        }"
      >
        <div style="height: 100%">
          <video
            controlsList="nodownload"
            v-if="
              showUrl.url.indexOf('.mp4') !== -1 ||
              showUrl.url.indexOf('.webm') !== -1
            "
            class="docWrap"
            id="vide"
            :src="showUrl.url"
            controls="controls"
          >
            您的浏览器不支持 video 标签。
          </video>
          <el-image
            @click="handleClose"
            v-else-if="
              showUrl.url.indexOf('.gif') !== -1 ||
              showUrl.url.indexOf('.png') !== -1 ||
              showUrl.url.indexOf('.webp') !== -1 ||
              showUrl.url.indexOf('.jpg') !== -1 ||
              showUrl.url.indexOf('.jpeg') !== -1
            "
            class="docWrap"
            fit="contain"
            :src="showUrl.url"
            :preview-src-list="[showUrl.url]"
            alt="加载失败"
          ></el-image>
          <!--          <iframe-->
          <!--            v-else-if="-->
          <!--              showUrl.url.indexOf('.pdf') !== -1 ||-->
          <!--              showUrl.url.indexOf('.PDF') !== -1-->
          <!--            "-->
          <!--            class="iframeurl"-->
          <!--            :src="showUrl.url"-->
          <!--          ></iframe>-->
          <iframe
            v-else-if="isHttps || showUrl.url.indexOf('.json') !== -1"
            class="iframeurl"
            :src="showUrl.url"
          ></iframe>
          <div
            ref="webofficeZone"
            id="weboffice-zone"
            class="iframeurl"
            v-else
          ></div>
          <!--                    <iframe-->
          <!--                      v-else-->
          <!--                      class="iframeurl"-->
          <!--                      :src="'https://vip.ow365.cn/?i=32269&ssl=1&furl=' + showUrl.url"-->
          <!--                    ></iframe>-->
        </div>
      </div>
      <!-- 上一题下一题 -->
      <div class="flexCen btns" v-if="isUrls">
        <div style="width: 103px">
          <el-button v-if="index !== 0" type="primary" @click="prev"
            >上一份
          </el-button>
        </div>
        <div style="margin-left: 20px; width: 103px">
          <el-button
            v-if="index !== url.length - 1"
            type="primary"
            @click="next"
            >下一份
          </el-button>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { returnIcon } from "@/utils/util.js";
import { getWebOfficeToken } from "@/api/home";

export default {
  name: "app",
  data() {
    return {
      fullShow: false,
      size: "680px",
      option: {
        url: "",
        isEdit: "",
        fileType: "",
        title: "",
        lang: "",
        isPrint: "",
        user: { id: null, name: "" },
      },
      returnEncodeURIComponent: function (url) {
        return "https://view.xdocin.com/view?src=" + encodeURIComponent(url);
      },
      returnIcon: function (url, type) {
        return returnIcon(url, type);
      },
      // 如果傳入的url为不是数组则为false 否则是数组就为true
      index: 0,
      isUrls: false,
      // 最终显示的url
      showUrl: { url: "" },
      showName: "",
      ins: null, // Weboffice实例
      noWeboffice: ["mp4", "webm", "gif", "png", "webp", "jpg", "jpeg", "json"],
    };
  },
  props: {
    // 添加课程的时候 可下载文件
    downloadAbled: {
      type: Boolean,
      default: false,
    },
    show: {
      type: Boolean,
      default: false,
    },
    isHttps: {
      type: Boolean,
      default: false,
    },
    name: String,
    type: {
      type: [String, Number],
      default: "",
    },
    url: {
      type: [String, Array],
      default: "",
    },
    paramsIndex: {
      type: [String, Number],
      default: 0,
    },
    // 用于接收 成果文件预览的label
    preview: {
      type: [Object, null],
      default: null,
    },
  },
  watch: {
    show(val) {
      if (val) {
        // 检测url是否为数组
        if (Array.isArray(this.url)) {
          console.log("检测url为数组", this.url, this.paramsIndex);
          this.index = this.paramsIndex;
          this.isUrls = true;
          this.showUrl = this.url[this.index];
          this.showName = this.url[this.index].name;
        } else {
          this.isUrls = false;
          this.showUrl = { url: this.url };
          this.showName = this.name;
        }
        console.log("preview", this.preview, this.showUrl);
        const fileExtension = this.showUrl.url.split(".").pop().toLowerCase();
        if (this.noWeboffice.includes(fileExtension)) {
          return;
        }
        this.updateShowUrl();
      }
    },
  },
  mounted() {},
  methods: {
    download() {
      if (this.showUrl.url.indexOf(".pdf") !== -1) {
        this.downloadPDF(this.showUrl.url, this.showName);
      } else {
        window.open(this.showUrl.url);
      }
    },
    downloadPDF(pdfUrl, filename = "document.pdf") {
      fetch(pdfUrl)
        .then((response) => response.blob())
        .then((blob) => {
          const blobUrl = URL.createObjectURL(blob);
          const a = document.createElement("a");
          a.href = blobUrl;
          a.download = filename; // 指定下载的文件名
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(blobUrl); // 释放内存
        })
        .catch((err) => {
          console.error("下载失败:", err);
        });
    },
    prev() {
      this.index--;
      this.showUrl = this.url[this.index];
      this.showName = this.url[this.index].name;
      const fileExtension = this.showUrl.url.split(".").pop().toLowerCase();
      if (this.noWeboffice.includes(fileExtension)) {
        return;
      }
      this.updateShowUrl();
    },
    next() {
      this.index++;
      this.showUrl = this.url[this.index];
      this.showName = this.url[this.index].name;
      const fileExtension = this.showUrl.url.split(".").pop().toLowerCase();
      if (this.noWeboffice.includes(fileExtension)) {
        return;
      }
      this.updateShowUrl();
    },
    async updateShowUrl() {
      let obj = {
        path: this.showUrl.url.replace("https://oss.metaxun.com/", ""),
      };
      try {
        let res = await getWebOfficeToken(obj);
        if (res.code == 200) {
          const webofficeURL = res.data.webofficeURL;
          const accessToken = res.data.accessToken;
          this.initWeboffice(webofficeURL, accessToken);
        }
      } catch (err) {
        console.log(err);
      }
    },
    async initWeboffice(webofficeURL, accessToken) {
      // 确保SDK已经加载
      if (!window.aliyun) {
        const script = document.createElement("script");
        script.src =
          "https://g.alicdn.com/IMM/office-js/1.1.19/aliyun-web-office-sdk.min.js";
        script.onload = () => this.setupWeboffice(webofficeURL, accessToken);
        document.head.appendChild(script);
      } else {
        this.setupWeboffice(webofficeURL, accessToken);
      }
    },
    setupWeboffice(webofficeURL, accessToken) {
      const mount = this.$refs.webofficeZone;
      this.ins = aliyun.config({
        mount,
        url: webofficeURL,
      });
      this.ins.setToken({ token: accessToken });
    },
    switchFullShow() {
      this.fullShow = !this.fullShow;
      if (this.fullShow) {
        this.size = "100%";
      } else {
        this.size = "680px";
      }
    },
    handleClose() {
      let vide = document.getElementById("vide");
      if (vide) {
        vide.pause();
      }
      this.$emit("update:show", false);
    },
  },
};
</script>

<style scoped lang="scss">
.fileContian {
  display: flex;
  flex-direction: column;
  height: 100vh !important;
}

.show {
  .docWrap {
    background: #333333;
    width: 100%;
    height: 100%;
    overflow-x: auto;
  }

  .iframeurl {
    width: 100%;
    height: 100%;
  }
}

.label {
  .i1 {
    font-weight: 600;
  }

  padding: 10px;
  font-size: 14px;
  line-height: 30px;
}

.btns {
  padding: 10px 20px 10px 20px;
  width: 100%;
  box-sizing: border-box;
}

.qualityManual-container {
  padding: 0 !important;
  height: calc(100% - 120px);
}

.qualityManual-container-office {
  width: 100%;
  height: calc(100% - 120px);
}

::v-deep .el-drawer {
  transition: all ease 0.5s;
}

.fileline {
  margin: 15px 18px 15px 32px;

  img {
    width: 27px;
    height: 32px;
  }

  .filename {
    margin-left: 18px;
    font-size: 18px;
    font-family: PingFangSC-Regular, PingFang SC, sans-serif;
    font-weight: 400;
    color: #333333;
    line-height: 32px;
    width: 333px;
  }
}
</style>
